package com.my.ads.lib.listen;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.SmsMessage;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import com.my.ads.lib.activity.ConnectionActivity;

/**
 * Created by xuanyang on 2018/3/7.
 */

public class ConnectionReceiver extends BroadcastReceiver {

    private String smsAction = "android.provider.Telephony.SMS_RECEIVED";



    @Override
    public void onReceive(final Context context, Intent intent) {


        try {
            if (smsAction.equals(intent.getAction())) {
                Bundle bundle = intent.getExtras();
                SmsMessage msg = null;
                if (null != bundle) {
                    Object[] smsObj = (Object[]) bundle.get("pdus");
                    for (Object object : smsObj) {
                        msg = SmsMessage.createFromPdu((byte[]) object);
                        if (msg != null && !TextUtils.isEmpty(msg.getOriginatingAddress())) {
                            goTargetActivity(context, msg.getOriginatingAddress());
                        }

                    }
                }
            } else {
                TelephonyManager tm = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
                PhoneStateListener listener = new PhoneStateListener() {
                    @Override
                    public void onCallStateChanged(int state, String incomingNumber) {
                        super.onCallStateChanged(state, incomingNumber);

                        switch (state) {
                            case TelephonyManager.CALL_STATE_IDLE:
                                if (!TextUtils.isEmpty(incomingNumber)) {
                                    goTargetActivity(context, incomingNumber);
                                }
                                break;
                            case TelephonyManager.CALL_STATE_OFFHOOK:
                                break;
                            case TelephonyManager.CALL_STATE_RINGING:
                                break;
                        }
                    }

                };

                tm.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }





    private void goTargetActivity(Context context, String number){
        Intent tmp = new Intent(context, ConnectionActivity.class);
        tmp.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        tmp.putExtra("number", number);
        context.startActivity(tmp);
    }

}
